package com.hdu.transmitableThreadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo {

    /**
     * 模拟 tomcat 线程池
     */
    static ExecutorService EXECUTOR = Executors.newFixedThreadPool(1);
    static ThreadLocal<String> TRACE_ID_HOLDER = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            String traceId = i + 1 + "";
            System.out.println("主线程获得 traceId : " + traceId);
            mockReq(traceId);
            // 主线程获得 traceId : 1
            // 主线程获得 traceId : 2
            // 主线程获得 traceId : 3
            // 子线程获得 traceId : 1
            // 子线程获得 traceId : 1
            // 子线程获得 traceId : 1
        }
    }

    /**
     * mock req
     *
     * @param traceId
     */
    public static void mockReq(String traceId) {
        TRACE_ID_HOLDER.set(traceId);
        EXECUTOR.execute(
                () -> System.out.println("子线程获得 traceId : " + TRACE_ID_HOLDER.get())
        );
    }
}
